package pers.zxk.jlytnews.servlet;

import pers.zxk.jlytnews.dao.UserDao;
import pers.zxk.jlytnews.dao.impl.UserDaoImpl;
import pers.zxk.jlytnews.entity.User;
import pers.zxk.jlytnews.manager.UserStateManager;
import pers.zxk.jlytnews.util.CommonUtil;
import pers.zxk.jlytnews.util.MD5Code;
import pers.zxk.jlytnews.util.ValidateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.sql.SQLException;


@MultipartConfig
public class UserServlet extends HttpServlet {
    private UserDao mUserDao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取能够与“url-pattern”中匹配的路径
        String method = req.getServletPath();

        //(此时处理的请求是查询 query.do)
        System.out.println("request.getServletPath()获取的值为: " + method);//输出 /query.do

        //2.通过字符串截取，把方法名 query 截取出来
        int i = method.lastIndexOf("/");
        method = method.substring(i + 1, method.length());

        System.out.println("截取后的值为： " + method);

        Method m = null;
        try {
            //3.获取当前类中名字为 method 的方法
            m = this.getClass().getDeclaredMethod(method,
                    HttpServletRequest.class, HttpServletResponse.class);

            //4.调用 method 方法
            m.setAccessible(true);
            m.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void register(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String rePassword = req.getParameter("repassword");
        if (ValidateUtil.validateEmpty(username) && ValidateUtil.validateEmpty(password) && ValidateUtil.validateEmpty(rePassword)) {
            if (password.equals(rePassword)) {
                User user = new User();
                user.setUsername(username);
                user.setPassword(new MD5Code().getMD5ofStr(password + username));
                user.setAdmin(0);
                try {
                    if (mUserDao.checkUserName(username)) {
                        if (mUserDao.registerUser(user)) {
                            CommonUtil.sendJsonData(resp, "注册成功", 0, "");
                        } else {
                            CommonUtil.sendJsonData(resp, null, 1, "注册失败");
                        }
                    } else {
                        CommonUtil.sendJsonData(resp, null, 1, "该用户名已被注册！");
                    }
                } catch (SQLException exception) {
                    exception.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "两次输入密码不同！");
            }
        } else {
            CommonUtil.sendJsonData(resp, null, 1, "必须输入用户名和密码！");
        }
    }

    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (ValidateUtil.validateEmpty(username) && ValidateUtil.validateEmpty(password)) {
            User user = new User();
            user.setUsername(username);
            user.setPassword(new MD5Code().getMD5ofStr(password + username));//加盐处理
            //System.out.println(user.getPassword());//用于测试输出加盐密码
            //更新数据并向客户端返回消息
            try {
                User userInfo = mUserDao.login(user);
                if (userInfo != null) {
                    UserStateManager.setLogin(req, userInfo);
                    CommonUtil.sendJsonData(resp, userInfo, 0, "");
                } else {
                    CommonUtil.sendJsonData(resp, null, 1, "用户名、密码错误");
                }
            } catch (Exception exception) {
                CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
            }
        } else {
            CommonUtil.sendJsonData(resp, null, 1, "必须输入用户名和密码！");
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        UserStateManager.setLogout(req);
        CommonUtil.sendJsonData(resp, null, 0, "");
    }

    public void changePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断登录
        if (!UserStateManager.isLogin(req)) {
            CommonUtil.sendJsonData(resp, null, 1, "请先登录！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String oldPassword = req.getParameter("oldpassword");
        String newPassword = req.getParameter("newpassword");
        String rePassword = req.getParameter("repassword");

        String username = (String) req.getSession().getAttribute("username");

        if (ValidateUtil.validateEmpty(oldPassword) && ValidateUtil.validateEmpty(newPassword) && ValidateUtil.validateEmpty(rePassword)) {
            if (newPassword.equals(rePassword)) {
                oldPassword = new MD5Code().getMD5ofStr(oldPassword + username);//加盐处理
                newPassword = new MD5Code().getMD5ofStr(newPassword + username);//加盐处理
                //更新数据并向客户端返回消息
                try {
                    if (mUserDao.updatePassword(username, oldPassword, newPassword)) {
                        CommonUtil.sendJsonData(resp, "密码修改成功！", 0, "");
                    } else {
                        CommonUtil.sendJsonData(resp, null, 1, "原密码不正确！");
                    }
                } catch (Exception exception) {
                    CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
                }
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "两次密码输入不同！");
            }
        } else {
            CommonUtil.sendJsonData(resp, null, 1, "必须输入用户名和密码！");
        }
    }

    public void updateNickname(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断登录
        if (!UserStateManager.isLogin(req)) {
            CommonUtil.sendJsonData(resp, null, 1, "请先登录！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String nickname = req.getParameter("nickname");

        String username = (String) req.getSession().getAttribute("username");

        if (ValidateUtil.validateEmpty(nickname)) {
            User user = new User();
            user.setUsername(username);
            user.setNickname(nickname);
            //更新数据并向客户端返回消息
            try {
                if (mUserDao.updateNickname(user)) {
                    CommonUtil.sendJsonData(resp, "昵称修改成功！", 0, "");
                } else {
                    CommonUtil.sendJsonData(resp, null, 1, "未知错误，请联系管理员！");
                }
            } catch (Exception exception) {
                CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
            }
        } else {
            CommonUtil.sendJsonData(resp, null, 1, "昵称不能为空！");
        }

    }

    public void updateGender(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断登录
        if (!UserStateManager.isLogin(req)) {
            CommonUtil.sendJsonData(resp, null, 1, "请先登录！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String gender = req.getParameter("gender");

        String username = (String) req.getSession().getAttribute("username");

        if (ValidateUtil.validateEmpty(gender)) {
            User user = new User();
            user.setUsername(username);
            user.setGender(gender);
            //更新数据并向客户端返回消息
            try {
                if (mUserDao.updateGender(user)) {
                    CommonUtil.sendJsonData(resp, "性别修改成功！", 0, "");
                } else {
                    CommonUtil.sendJsonData(resp, null, 1, "未知错误，请联系管理员！");
                }
            } catch (Exception exception) {
                CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
            }
        } else {
            CommonUtil.sendJsonData(resp, null, 1, "性别不能为空！");
        }

    }

    public void updatePhone(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断登录
        if (!UserStateManager.isLogin(req)) {
            CommonUtil.sendJsonData(resp, null, 1, "请先登录！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String phone = req.getParameter("phone");

        String username = (String) req.getSession().getAttribute("username");

        User user = new User();
        user.setUsername(username);
        user.setPhone(phone);
        //更新数据并向客户端返回消息
        try {
            if (mUserDao.updatePhone(user)) {
                CommonUtil.sendJsonData(resp, "手机号码修改成功！", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "未知错误，请联系管理员！");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
        }
    }

    public void updateDept(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断登录
        if (!UserStateManager.isLogin(req)) {
            CommonUtil.sendJsonData(resp, null, 1, "请先登录！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String dept = req.getParameter("dept");

        String username = (String) req.getSession().getAttribute("username");

        User user = new User();
        user.setUsername(username);
        user.setDept(dept);
        //更新数据并向客户端返回消息
        try {
            if (mUserDao.updateDept(user)) {
                CommonUtil.sendJsonData(resp, "所在单位修改成功！", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "未知错误，请联系管理员！");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
        }
    }

    public void updateIcon(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //判断登录
        if (!UserStateManager.isLogin(req)) {
            CommonUtil.sendJsonData(resp, null, 1, "请先登录！");
            return;
        }
        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String iconPath = "";
        Part part = req.getPart("icon");
        if (part.getSubmittedFileName() != null) {//如果能拿到part中保存的图片名称，再保存图片
            iconPath = CommonUtil.saveImage(part);//保存图片，返回图片路径
        }

        String username = (String) req.getSession().getAttribute("username");

        User user = new User();
        user.setUsername(username);
        user.setIcon(iconPath);
        //更新数据并向客户端返回消息
        try {
            if (mUserDao.updateIcon(user)) {
                CommonUtil.sendJsonData(resp, "头像修改成功！", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "未知错误，请联系管理员！");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
        }
    }

}
